package View;

import Controller.POSSystem;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class PurchaseFrame extends JFrame{
    private JButton putButton = new JButton("输入");
    private JButton finishButton = new JButton("结算");
    private JPanel listPanel = new JPanel();//上半部分显示购物列表
    private JPanel inputPanel = new JPanel();//下半部分显示加购输入
    private JTextArea listText = new JTextArea();
    private JLabel idLabel = new JLabel("ID");
    private JLabel qtyLabel = new JLabel("数量");
    private JTextField idInput = new JTextField();
    private JTextField qtyInput = new JTextField();
    private static PurchaseFrame instance;

    private PurchaseFrame() {

        setTitle("加购窗口");
        setSize(330, 450);

        putButton.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                enterItem();
            }
        });
        finishButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                endPurchase();
            }
        });

        listText.setEditable(false);
        listPanel.add(listText);

        inputPanel.setLayout(new GridLayout(3,2));
        inputPanel.add(idLabel);
        inputPanel.add(idInput);
        inputPanel.add(qtyLabel);
        inputPanel.add(qtyInput);
        inputPanel.add(putButton);
        inputPanel.add(finishButton);

        Container pane = getContentPane();
        pane.setLayout(new BorderLayout());
        pane.add(listPanel, BorderLayout.NORTH);
        pane.add(inputPanel, BorderLayout.SOUTH);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void endPurchase() {
        POSSystem.getInstance().endPurchase();
        conceal();
    }

    private void enterItem() {
        listText.setText("商品名\t零售价\t数量\t金额");
        listText.append(POSSystem.getInstance().
                enterItem(Integer.parseInt(idInput.getText()), Integer.parseInt(qtyInput.getText())));//回显已购商品
        idInput.setText("");
        qtyInput.setText("");
    }

    public static PurchaseFrame getInstance() {
        if (instance == null) {
            instance = new PurchaseFrame();
        }
        return instance;
    }

    public void display() {
        if (!isVisible()) {
            listText.setText("商品名\t零售价\t数量\t金额");
            setVisible(true);
        }
    }

    public void conceal() {
        if (isVisible())
            setVisible(false);
    }
}
